package com.app.activitys;


import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

import org.apache.http.util.ByteArrayBuffer;

import com.app.entidades.Bar;
import com.example.applucianokikao.R;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

public class ActivityDetalhesBar extends FragmentActivity{

	private Bar bar;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_detalhes_bar);
		
		Bundle extras = getIntent().getExtras();
		Bundle valor = extras.getBundle("bar_bundle");
		bar = (Bar) valor.getSerializable("bar_objeto");
		
		TextView descricao = (TextView) findViewById(R.id.txt_desc_deta_bar);
		TextView horario = (TextView) findViewById(R.id.txt_horario_bar);
		TextView telefone = (TextView) findViewById(R.id.txt_telefone_bar);
		TextView email = (TextView) findViewById(R.id.txt_email_bar);
		TextView site = (TextView) findViewById(R.id.txt_site_bar);
		TextView endereco = (TextView) findViewById(R.id.txt_endereco_bar);
		ImageView capa = (ImageView) findViewById(R.id.img_capa_bar);
		
		final ImageButton button_facebook = (ImageButton) findViewById(R.id.btn_face_bar);
		final ImageButton twt = (ImageButton) findViewById(R.id.btn_twt_bar);
		final ImageButton fours = (ImageButton) findViewById(R.id.btn_fours_bar);
		
		if(bar.getFb().isEmpty()){
			button_facebook.setEnabled(false);
		}
		
		if(bar.getTw().isEmpty()){
			twt.setEnabled(false);
		}
		
		if(bar.getFoursquare().isEmpty()){
			fours.setEnabled(false);
		}					

		
		button_facebook.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Uri uri = Uri.parse(bar.getFb());
				Intent intent = new Intent(Intent.ACTION_VIEW, uri);
				startActivity(intent);
			}
		});
		
		
		twt.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Uri uri = Uri.parse(bar.getTw());
				Intent intent = new Intent(Intent.ACTION_VIEW, uri);
				startActivity(intent);
			}
		});
		
		fours.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Uri uri = Uri.parse(bar.getFoursquare());
				Intent intent = new Intent(Intent.ACTION_VIEW, uri);
				startActivity(intent);
			}
		});
		
		
		Bitmap m = buscaImagem(nomeImagem(bar.getLogotipo()));
		
		if(m==null){
			baixaImagem(bar.getLogotipo());
			capa.setImageResource(R.drawable.foto_banda_padrao);
		}else{
			capa.setImageBitmap(m);
		}
		
		SupportMapFragment mapFragmente = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map_local_bar);
		GoogleMap map = mapFragmente.getMap();
		
		map.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
		
		double lat = Double.valueOf(bar.getLat());
		double lng = Double.valueOf(bar.getLng());
		
		LatLng latlng = new LatLng(lat,lng);
		CameraPosition position = new CameraPosition.Builder().target(latlng).zoom(21).build();
		CameraUpdate update = CameraUpdateFactory.newCameraPosition(position);
		map.moveCamera(update);
		adicionarMarket(map, latlng);
		
		descricao.setText(bar.getDescricao());
		horario.setText(bar.getHorarios());
		telefone.setText(bar.getFone());
		email.setText(bar.getEmail());
		site.setText(bar.getSite());
		endereco.setText(bar.getEndereco());
	
	}
	
	private void adicionarMarket(GoogleMap map, LatLng latLng){
		MarkerOptions markerOptions = new MarkerOptions();
		markerOptions.position(latLng).title("Marcador").snippet("Ponto");
		Marker marker = map.addMarker(markerOptions);
	}
	
	private void baixaImagem(final String url) {
	      System.out.println("baixando");
			new Thread(new Runnable() {	
				@Override
				public void run() {
				        try {
				        	URL aURL = new URL(url);
						    URLConnection conn = aURL.openConnection();
						    conn.connect();
						        
						    
						    InputStream is = conn.getInputStream();
						    final BufferedInputStream bis = new BufferedInputStream(is);
						    
						    String nome = nomeImagem(url);
						    
						    
						    File file = new File(Environment.getExternalStorageDirectory()+"/Kikao/");

						    
						    FileOutputStream fos = new FileOutputStream(file+"/"+nome);
						    
						    // fos= (FileOutputStream) contexto.getContentResolver().openOutputStream(Uri);
						    fos.write(getBytes(bis));
						    fos.flush();
						    fos.close();
						    System.out.println("Baixou e Salvou");
						    bis.close();
						    is.close();
					   } catch (IOException e) {
						      Log.e("ImagemButton", "Error getting bitmap", e);
					   }
				}
	    	}).start();
	    }
		
		private Bitmap buscaImagem(String nomeImagem){
			Bitmap bmp=null;
				
			    File file = new File(Environment.getExternalStorageDirectory()+"/Kikao/"+nomeImagem);
			    if(file.exists()){
			    	System.out.println("existe");
			    	bmp = BitmapFactory.decodeFile(file.getPath());
			    }else{
			    	System.out.println("não existe");
			    }
				return bmp;
			
		}
		
		private String nomeImagem(String link){
			String[] valores = link.split("/");
			return valores[valores.length-1];
		}
		
		
		public byte[] getBytes(BufferedInputStream bis){
			ByteArrayBuffer baf = new ByteArrayBuffer(50);

			int count = 0;

			try {
				while((count = bis.read()) != -1){
					baf.append((byte) count);
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			return baf.toByteArray();
		}

	
}
